const express = require("express");
const moment = require("moment");
const { LOGGER, EXPRESS_LOGGER } = require("./log/logger.js");
const TopClient = require("./lib/api/topClient.js").TopClient;
LOGGER.info(`start`);
const app = express();
const port = 3000;
const client = new TopClient({
  appkey: "28876583",
  appsecret: "DHxcbhi2euoO0zJSn9VrMztASAJDHxcHxcbhi2euoO0",
  url: "https://eco.woyueche.com/router/rest",
});
app.get("/", (req, res) => {
  res.send("Hello World!");
  EXPRESS_LOGGER(req, res);
});
const sessionMap = {
  "2号店": '62014038684ZZc0bfhf28bc79b4dbc726e43f41deb9b224453632116',
  "3号店": '620102856c93752362083d056043dce0dca4ZZ824ZZfe92457424510',
  "4号店": '6201113c17e07fe89fb0ace609ZZd32802907b62132683f2212788263596',
  "5号店": '62025094872f03d36ZZa99df90419b6e31652c043190d1a2484525269',
}
app.get("/allorder/:shop", (req, res) => {
  EXPRESS_LOGGER(req, res);  
  const shop = req.params.shop;
  if(shop === '转账') {
    return res.json({payment: -3})
  }
  const start_modified = moment(
    new Date().getTime() - 1000 * 60 * 60 * 24
  ).format("YYYY-MM-DD hh:mm:ss");
  const end_modified = moment().format("YYYY-MM-DD hh:mm:ss");
  console.log(start_modified, end_modified);
  client.execute(
    "taobao.trades.sold.increment.get",
    {
      fields: "tid,type,status,payment,orders,rx_audit_status, modified",
      start_modified,
      end_modified,
      page_no: "1",
      page_size: "50",
      session: sessionMap[shop] || "62014038684ZZc0bfhf28bc79b4dbc726e43f41deb9b224453632116",
    },
    async (error, response) => {
      if (!error) {
        LOGGER.info(JSON.stringify(response));
        if (response.total_results > 0) {
          const trades = response.trades?.trade;
          const orderList = trades.map((item) => {
            const modified = item.modified;
            const orderDetail = item.orders.order[0];
            const {
              oid,
              title,
              sku_properties_name,
              num,
              status,
              total_fee,
              part_mjz_discount,
              payment,
              end_time,
              consign_time,
              refund_status,
            } = orderDetail;
            return {
              oid,
              title,
              sku_properties_name,
              num,
              status,
              total_fee,
              part_mjz_discount,
              payment,
              consign_time,
              end_time,
              modified,
              refund_status,
            };
          });
          res.json(orderList);
        }
      } else {
        LOGGER.info(JSON.stringify(error));
        console.log(error);
        res.send("-1");
      }
    }
  );
});


app.get("/all/:shop-:id", (req, res) => {
  EXPRESS_LOGGER(req, res);
  const tid = req.params.id;
  const shop = req.params.shop;
  console.log(shop);
  console.log(sessionMap[shop]);
  if(shop === '转账') {
    return res.json({payment: -3})
  }
  console.log(1111)
  console.log(shop, sessionMap[shop])
  console.log(sessionMap[shop])
  if (!/^\d{18,20}$/.test(tid)) {
    return res.json({ payment: -3 });
  }
  client.execute(
    "taobao.trade.fullinfo.get",
    {
      fields:
        "tid,type,title,status,payment,orders,promotion_details,created,pay_time,end_time,consign_time,modified,adjust_fee,total_fee,buyer_memo,buyer_message,receiver_mobile,receiver_phone",
      tid,
      session: sessionMap[shop] || "6201119c092323ae50f28e26cc0ZZce4fh2dd0e60d3e0e8453632116",
    },
    async (error, response) => {
      if (!error) {
        LOGGER.info(JSON.stringify(response));
        console.log(response);
        if (response.trade) {
          const trades = response.trade;
          const {
            tid,
            type,
            title,
            status,
            payment,
            orders,
            promotion_details,
            created,
            pay_time,
            end_time,
            consign_time,
            modified,
            adjust_fee,
            total_fee,
            buyer_memo,
            buyer_message,
            receiver_mobile,
            receiver_phone,
          } = trades;
          console.log(tid);
          console.log(orders);
          const { sku_properties_name, num, part_mjz_discount, refund_status } =
            orders.order[0];
          const isOKORDER = [
            "WAIT_SELLER_SEND_GOODS",
            "WAIT_BUYER_CONFIRM_GOODS",
            "TRADE_FINISHED",
          ].includes(status);
          res.json({
            tid,
            type,
            title,
            sku_properties_name,
            num,
            part_mjz_discount,
            payment: isOKORDER ? payment : "-1",
            status,
            // orders,
            promotion_details,
            created,
            pay_time,
            end_time,
            consign_time,
            modified,
            adjust_fee,
            total_fee,
            buyer_memo,
            buyer_message,
            receiver_mobile,
            receiver_phone,
            refund_status,
          });
        }
      } else {
        LOGGER.info(JSON.stringify(error));
        console.log("error:");
        console.log(error);
        res.json({ payment: -2 });
      }
    }
  );
});

app.use(EXPRESS_LOGGER);
app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});

// http://127.0.0.1/?code=hfUdyeOeK1jjywM6KHJLJDjt9056816
